package com.dudu.util;

import com.dudu.exception.BusinessException;
import com.dudu.exception.ErrorCode;
import com.dudu.exception.PermissionDeniedException;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;


@Slf4j
public class ControllerUtils {

    public static interface ActionHandler {
        WebResponse<?> getResponse() throws Exception;
    }

    public static String getRemortIP(HttpServletRequest request) {
        if (request.getHeader("x-forwarded-for") == null) {
            return request.getRemoteAddr();
        }
        return request.getHeader("x-forwarded-for");
    }

    public static WebResponse<?> doHandler(ActionHandler handler, String actionName, Object params) {
        try {
            log.info("{} request params: {}", actionName, params);
            long current = System.currentTimeMillis();
            WebResponse<?> response = handler.getResponse();
            log.info("{}, data={}, cost:[{}ms]", actionName, response.getData(), System.currentTimeMillis() - current);
            return response;
        } catch (BusinessException e) {
            log.warn("catch business exception:", e);
            log.warn("{}, catch  BusinessException:{} {}", actionName, e, e.getErrorCode());
            return WebResponseHelper.error(e.getErrorCode());
        } catch (IllegalArgumentException e) {
            log.warn("catch illegal exception:", e);
            log.warn("{}, catch  IllegalArgumentException:{} {}", actionName, e, e.getMessage());
            return WebResponseHelper.error(ErrorCode.PARAMS_ERROR);
        }  catch (PermissionDeniedException e) {
            log.error("cat PermissionDeniedException:", e);
            log.error("{}, catch  Exception:{} {}", actionName, e, e.getMessage());
            return WebResponseHelper.error(ErrorCode.PERMISSION_DENIED_ERROR);
        }catch (Exception e) {
            log.error("cat exception:", e);
            log.error("{}, catch  Exception:{} {}", actionName, e, e.getMessage());
            return WebResponseHelper.error(ErrorCode.SYSTEM_ERROR);
        }
    }

}
